package com.boco.service.impl;

import com.boco.common.util.HttpUtils;
import com.boco.config.BocoProperties;
import com.boco.service.SmsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author pandengke/pdkkpdk@163.com
 * @date 2018/11/29
 */
@Component
public class SmsServiceImpl implements SmsService {


    @Resource
    BocoProperties bocoProperties;

    /**
     * 发送短信
     *
     * @param phoneNos 手机号数组
     * @param context  短信内容
     * @return string
     * @throws Exception 抛出异常
     */
    @Override
    public String sendSMS(String[] phoneNos, String context) throws UnsupportedEncodingException {
        String url = getSendUrl(String.join(",", phoneNos), context);
        if (!bocoProperties.getSms().getEnable()) return null;
        return HttpUtils.postByRestTemplate(url, context);
    }

    /**
     * 单个手机发送短信验证消息
     *
     * @param phone
     * @param content
     * @return
     * @throws Exception
     */
    public String sendSMS(String phone, String content) throws UnsupportedEncodingException {
        return sendSMS(new String[]{phone}, content);
    }

    /**
     * 获取短信发送URL
     *
     * @param mobile  手机号
     * @param content 短信发送内容
     * @return string
     * @throws UnsupportedEncodingException 不支持字符集异常
     */
    private String getSendUrl(String mobile, String content) throws UnsupportedEncodingException {
        BocoProperties.Sms sms = bocoProperties.getSms();
        StringBuilder sb = new StringBuilder(sms.getUrl());
        sb.append("?")
                .append("name=").append(sms.getUserName())
                .append("&pwd=").append(sms.getPwd())
                .append("&mobile=").append(mobile)
                .append("&content=").append(URLEncoder.encode(content, "UTF-8"))
                .append("&stime=")
                .append("&sign=").append(URLEncoder.encode(sms.getSign(), "UTF-8"))
                .append("&type=pt&extno=0916");
        System.out.println("sb:" + sb.toString());
        return sb.toString();
    }
}
